# coding=utf-8
'''
Created on 2013-5-18

@author: Microacup
'''
<<<<<<< HEAD
import handler.base

class LoginHandler(handler.base.BaseHandler):
    def get(self):
        self.render("login.html")
        
    def post(self):
        self.redirect("/")
        # TODO ...验证用户
        
class SignHandler(handler.base.BaseHandler):
    def get(self):
        self.render("login.html")
        
    def post(self):
        self.redirect("/")
=======
from handler.base import BaseHandler
from forms.user import LoginForm
from forms.user import SignupForm
from model.user import User
from model.user import Profile
from datetime import datetime

import tornado.escape
import simplejson
import hashlib
import re
import uuid

def dologin(self, userinfo):
    print(userinfo)
    self.session["userinfo"] = userinfo
    self.session.save()
    self.set_secure_cookie("user", tornado.escape.json_encode(userinfo))

def dologout(self):
    self.session["userinfo"] = None
    self.session.save()
    self.clear_cookie("user")

class LoginHandler(BaseHandler):
    
    def get(self, template_variables = {}):
        dologout(self)
        self.render("login.html", **template_variables)
        
    def post(self, template_variables = {}):
        form = LoginForm(self)
        if not form.validate():
            self.get({"errors": form.errors})
            return
        
        name = form.name.data;
        secure_password_md5 = hashlib.md5(form.password.data.encode(encoding='utf_8', errors='strict')).hexdigest()
        
        if re.match(r'\w+((-w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+', name): # 邮箱
            user = self.userSerivice.get_user_by_email_and_password(name, secure_password_md5)
        else:
            user = self.userSerivice.get_user_by_username_and_password(name, secure_password_md5)
#         print(user)
#         user = self.userSerivice.get_user_by_username('wangxiaoming')
#         user = self.userSerivice.get_user_by_uuid('fa79b6c06b9b11e3b594005056c00001')
        if user:
            curr_user = user[0]
            curr_user.profile.lastlogtime = datetime.now()
            self.userSerivice.save(curr_user)
            
            user_info = simplejson.loads(curr_user.to_json())
#             self.set_secure_cookie("user", tornado.escape.json_encode(user_info))
            dologin(self, user_info)
            self.redirect("/")
        else:
            template_variables["errors"] = {"invalid_username_or_password": ["用户名/邮箱或者密码不匹配"]}
            self.get(template_variables)

class LogoutHandler(BaseHandler):
    def get(self):
        dologout(self)
        self.redirect("/")
        
class SignHandler(BaseHandler):
    def get(self, template_variables = {}):
        dologout(self)
        self.render("login.html", **template_variables)
        
    def post(self, template_variables = {}):
        form = SignupForm(self)
#         print(', '.join(['%s:%s' % item for item in form.__dict__.items()]))
        name = form.signname.data
        email = form.signemail.data
        if not form.validate():
            self.get({"errors": form.errors})
            return
        userinfo = self.userSerivice.get_user_by_username(name)
        if userinfo:
            template_variables["errors"] ={}
            template_variables["errors"]["username"] = ['该用户名已经被注册过']
            self.get(template_variables)
            return
        userinfo = self.userSerivice.get_user_by_email(email)
        if userinfo:
            template_variables["errors"] ={}
            template_variables["errors"]["email"] = ['该邮箱已经被注册过']
            self.get(template_variables)
            return
        
        secure_password_md5 = hashlib.md5(form.signpassword.data.encode(encoding='utf_8', errors='strict')).hexdigest()

        # 走到这里说明用户提交的信息时被接受的，可以注册
        now = datetime.now()
        profile = Profile(avatar='/static/avatar/avatar96.jpg', regtime=now, lastlogtime=now)
        user = User(
            uuid = uuid.uuid1(),
            mid = self.metaService.get_current_user_count() + 1,
            username = name,
            email = email,
            password = secure_password_md5,
            nickname = name, 
            profile = profile
        )

        self.userSerivice.save(user)
        self.metaService.set_current_user_count(user.mid)
        
        userinfo = simplejson.loads(user.to_json())
        dologin(self, userinfo)
#         self.set_secure_cookie("user", tornado.escape.json_encode(userinfo))
        self.redirect("/")
>>>>>>> refs/heads/dev
